package cn.itcast.wushangxiantu.Activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.itcast.wushangxiantu.BaseAdapter.XinxiAdapter;
import cn.itcast.wushangxiantu.Dialog.QianDaoDialog;
import cn.itcast.wushangxiantu.Fragment.home.MainCity;
import cn.itcast.wushangxiantu.Fragment.home.NongTian;
import cn.itcast.wushangxiantu.Fragment.home.SenLin;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.MyBean;
import cn.itcast.wushangxiantu.MyBroadCastReceiver;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.PlayingMusicServices;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.Util;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView ivTouXiang;
    private TextView tvName;
    private TextView tvMoney;
    private FrameLayout flMainCity;
    private ListView lv;
    private ImageView ivLiaoTian;
    private TextView tvSenLin;
    private TextView tvZhuCheng;
    private TextView tvNongYuan;
    private LinearLayout ll;
    private FrameLayout fl;
    private Socket socket;
    int num = 1;
    private TextView tvJingyan;
    private NeedStopThread thread;
    private NeedStopThread2 thread2;
    private XinxiAdapter adapter;
    private boolean Working = true;
    private ArrayList<MyBean> list;
    private boolean sview = false;

    private FragmentManager mFm;
    private ArrayList<Fragment> mFragmentList = new ArrayList<Fragment>();
    private String[] mFragmentTagList = {"senlin", "zhuchen", "nongtian"};
    private Fragment mCurrentFragmen = null;  // 记录当前显示的Fragment
    private Button tvQianDao;
    private Button tvXiuGaiMiMa;
    private Button tvBack;
    private ScrollView Sview;
    private String daqu;
    private String gonglue[];
    private TextView tvGongLue;
    private boolean musicWorking=true;

    /**
     * 规定开始音乐、暂停音乐、结束音乐的标志
     */
    public static final int PLAT_MUSIC = 1;
    public static final int PAUSE_MUSIC = 2;
    public static final int STOP_MUSIC = 3;
    private MyBroadCastReceiver receiver;
    private ImageView ivMusic;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        initView();
        playingmusic(PLAT_MUSIC);
        Working = true;
        if (thread == null) {
            thread = new NeedStopThread();
            thread.start();
            thread2 = new NeedStopThread2();
            thread2.start();
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @SuppressLint("ResourceAsColor")
    private void initView() {
        receiver = new MyBroadCastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.complete");
        registerReceiver(receiver, filter);

        Resources res = getApplication().getResources();
        gonglue = res.getStringArray(R.array.gonglue);

        SenLin senLin = new SenLin(this);
        NongTian nongTian = new NongTian(this);
        MainCity mainCity = new MainCity(this);

        mFragmentList.add(0, senLin);
        mFragmentList.add(1, mainCity);
        mFragmentList.add(2, nongTian);

        mCurrentFragmen = mFragmentList.get(1);

        ivTouXiang = (ImageView) findViewById(R.id.ivTouXiang);
        tvName = (TextView) findViewById(R.id.tvName);
        tvMoney = (TextView) findViewById(R.id.tvMoney);
        flMainCity = (FrameLayout) findViewById(R.id.fl);
        lv = (ListView) findViewById(R.id.lv);
        ivLiaoTian = (ImageView) findViewById(R.id.ivLiaoTian);
        tvSenLin = (TextView) findViewById(R.id.tvSenLin);
        tvZhuCheng = (TextView) findViewById(R.id.tvZhuCheng);
        tvNongYuan = (TextView) findViewById(R.id.tvNongYuan);
        ll = (LinearLayout) findViewById(R.id.ll);
        tvGongLue = (TextView) findViewById(R.id.tvGongLue);
        adapter = new XinxiAdapter(this);
        list = new ArrayList<>();
        tvSenLin.setOnClickListener(this);
        tvZhuCheng.setOnClickListener(this);
        tvNongYuan.setOnClickListener(this);
        ivLiaoTian.setOnClickListener(this);
        ivTouXiang.setOnClickListener(this);

        tvMoney.setText("金钱：" + Login.getUser().getMoney());
        tvName.setText("LV:" + Login.getUser().getDj() + " " + Login.getUser().getName());

        if (Login.getUser().getDj() > 80) {
            tvName.setBackground(getResources().getDrawable(R.color.renwudj5));
        } else if (Login.getUser().getDj() >= 60) {
            tvName.setBackground(getResources().getDrawable(R.color.renwudj4));
        } else if (Login.getUser().getDj() >= 40) {
            tvName.setBackground(getResources().getDrawable(R.color.renwudj3));
        } else if (Login.getUser().getDj() >= 20) {
            tvName.setBackground(getResources().getDrawable(R.color.renwudj2));
        } else if (Login.getUser().getDj() >= 1) {
            tvName.setBackground(getResources().getDrawable(R.color.renwudj1));
        }

        mFm = getFragmentManager();
        FragmentTransaction transaction = mFm.beginTransaction();
        transaction.add(R.id.fl, mCurrentFragmen, mFragmentTagList[1]);
        transaction.commitAllowingStateLoss();

        fl = (FrameLayout) findViewById(R.id.fl);
        fl.setOnClickListener(this);
        tvJingyan = (TextView) findViewById(R.id.tvJingyan);
        tvJingyan.setOnClickListener(this);
        tvGongLue.setOnClickListener(this);
        tvJingyan.setText("修为：" + Login.getUser().getJy() + "/" + (Login.getUser().getDj() * Login.getUser().getDj() * Login.getUser().getDj() * Login.getUser().getDj() / 5 + 10));
        tvQianDao = (Button) findViewById(R.id.tvQianDao);
        tvQianDao.setOnClickListener(this);
        tvXiuGaiMiMa = (Button) findViewById(R.id.tvXiuGaiMiMa);
        tvXiuGaiMiMa.setOnClickListener(this);
        tvBack = (Button) findViewById(R.id.tvBack);
        tvBack.setOnClickListener(this);
        Sview = (ScrollView) findViewById(R.id.Sview);

        daqu = "【一区】";
        if (OkhttpUtil.URL_LOG.equals(OkhttpUtil.URL_LOGs[0])) {
            daqu = "【一区】";
        } else if (OkhttpUtil.URL_LOG.equals(OkhttpUtil.URL_LOGs[1])) {
            daqu = "【二区】";
        }
        ivMusic = (ImageView) findViewById(R.id.ivMusic);
        ivMusic.setOnClickListener(this);
    }

    private void playingmusic(int type) {
        //启动服务，播放音乐
        Intent intent = new Intent(this, PlayingMusicServices.class);
        intent.putExtra("type", type);
        startService(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvZhuCheng:
                if (num != 1) {
                    changeMenu(1);
                    switchFragment(mFragmentList.get(1), mFragmentTagList[1]);
                    num = 1;
                }
                break;
            case R.id.tvNongYuan:
                if (num != 2) {
                    changeMenu(2);
                    switchFragment(mFragmentList.get(2), mFragmentTagList[2]);
                    num = 2;
                }
                break;
            case R.id.tvSenLin:
                if (num != 0) {
                    changeMenu(0);
                    switchFragment(mFragmentList.get(0), mFragmentTagList[0]);
                    num = 0;
                }
                break;
            case R.id.ivLiaoTian:
                GeneralDialog("liaotian");
                break;
            case R.id.tvQianDao:
                userqiandao(Login.getUser().getUsernumber());
                break;
            case R.id.tvXiuGaiMiMa:
                GeneralDialog();
                break;
            case R.id.tvBack:
                Intent intent = null;
                intent = new Intent(MainActivity.this, Login.class);
                startActivity(intent);
                finish();
                break;
            case R.id.ivTouXiang:
                //默认false
                if (sview) {
                    Sview.fullScroll(ScrollView.FOCUS_UP);//滚动到顶部
                    sview = false;
                } else {
                    Sview.fullScroll(ScrollView.FOCUS_DOWN);
                    sview = true;
                }
                break;
            case R.id.tvGongLue:
                int index = (int) (Math.random() * gonglue.length);
                ToastUtil.toastLong(getApplicationContext(), gonglue[index]);
                break;
            case R.id.ivMusic:
                if (musicWorking){
                    playingmusic(STOP_MUSIC);
                    ivMusic.setBackground(getDrawable(R.drawable.musci2));
                    musicWorking=false;
                }else {
                    playingmusic(PLAT_MUSIC);
                    ivMusic.setBackground(getDrawable(R.drawable.music1));
                    musicWorking=true;
                }
                break;
        }
    }

    private void qiandao(String week, String all) {
        final QianDaoDialog qianDaoDialog = new QianDaoDialog(MainActivity.this);
        qianDaoDialog.setSingle(true).setMessageAll(all).setMessageWeek(week).setOnClickBottomListener(new QianDaoDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                qianDaoDialog.dismiss();
            }

            @Override
            public void onNegtiveClick() {
                qianDaoDialog.dismiss();
            }
        }).show();
    }

    // 转换Fragment
    void switchFragment(Fragment to, String tag) {
        if (mCurrentFragmen != to) {
            FragmentTransaction transaction = mFm.beginTransaction();
            if (!to.isAdded()) {
                // 没有添加过:
                // 隐藏当前的，添加新的，显示新的
                transaction.hide(mCurrentFragmen).add(R.id.fl, to, tag).show(to);
            } else {
                // 隐藏当前的，显示新的
                transaction.hide(mCurrentFragmen).show(to);
            }
            mCurrentFragmen = to;
            transaction.commitAllowingStateLoss();

        }
    }

    // 当activity非正常销毁时被调用
    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        // 重置Fragment，防止当内存不足时导致Fragment重叠
        updateFragment(outState);
    }

    // 重置Fragment
    private void updateFragment(Bundle outState) {

        mFm = getFragmentManager();
        if (outState == null) {
            FragmentTransaction transaction = mFm.beginTransaction();
            SenLin senLin = new SenLin(this);
            mCurrentFragmen = senLin;
            transaction.add(R.id.fl, senLin, mFragmentTagList[0]).commitAllowingStateLoss();
        } else {
            // 通过tag找到fragment并重置
            SenLin senLin = (SenLin) mFm.findFragmentByTag(mFragmentTagList[0]);
            MainCity mainCity = (MainCity) mFm.findFragmentByTag(mFragmentTagList[1]);
            NongTian nongTian = (NongTian) mFm.findFragmentByTag(mFragmentTagList[2]);
            mFm.beginTransaction().show(senLin).hide(mainCity).hide(nongTian);
        }
    }

    public void changeMenu(int num) {
        tvSenLin.setTextSize(20);
        tvZhuCheng.setTextSize(20);
        tvNongYuan.setTextSize(20);

        switch (num) {
            case 0:
                tvSenLin.setTextSize(28);
                break;
            case 1:
                tvZhuCheng.setTextSize(28);
                break;
            case 2:
                tvNongYuan.setTextSize(28);
                break;
        }
    }

    private void GeneralDialog(final String title) {
        /**
         * 编辑框
         * 1标题
         */
        AlertDialog dialog;
        final EditText editText = new EditText(this);
        editText.setLines(1);
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        String content = null;
        if (title.equals("liaotian")) {
            content = "聊天内容(2-20字)";
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(content)
                .setView(editText)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (title.equals("liaotian")) {
                            if (editText.getText().toString().trim().length() > 20) {
                                ToastUtil.toast(MainActivity.this, "长度过长了");
                                return;
                            } else if (editText.getText().toString().trim().length() < 1) {
                                ToastUtil.toast(MainActivity.this, "长度过短了");
                                return;
                            } else if (Login.getUser().getDj() < 15) {
                                ToastUtil.toast(MainActivity.this, "15级开放");
                                return;
                            }
                        }
                        fasong(editText.getText().toString().trim(), 0);
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void GeneralDialog() {
        /**
         * 编辑框
         * 1标题
         */
        AlertDialog dialog;
        final EditText editText = new EditText(this);
        editText.setLines(1);
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        String content = "输入新的密码";
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(content)
                .setView(editText)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
                        Matcher m = p.matcher(editText.getText().toString().trim());
                        if (editText.getText().toString().trim().length() > 12) {
                            ToastUtil.toast(MainActivity.this, "长度过长了");
                            return;
                        } else if (editText.getText().toString().trim().length() < 1) {
                            ToastUtil.toast(MainActivity.this, "长度过短了");
                            return;
                        }
                        if (m.find()) {
                            ToastUtil.toast(MainActivity.this, "不能带有中文");
                            return;
                        }
                        setPasswrod(Login.getUser().getUsernumber(), Login.getUser().getPassword(), editText.getText().toString().trim());
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void setPasswrod(String usernumber, String password, String newpassword) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&passWord=" + password + "&need=setpassword" + "&newpassword=" + newpassword, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("Logon11111", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("jack", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

    private void userqiandao(String usernumber) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&need=qiandao", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("Logon11111", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("jack", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 4;
                handler.sendMessage(message);
            }
        });
    }

    private void fasong(final String data, final int num) {
        //内容是什么，发送者是否选择为管理员
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OutputStream outputStream = socket.getOutputStream();
                    if (num == 1 && data != null && data.trim().length() >= 1) {
                        outputStream.write((socket.getLocalPort() + "//" + "denglu" + daqu + Util.getIMEI(MainActivity.this) + "//" + Login.getUser().getName() + "//" + -1).getBytes("utf-8"));
                    } else if (num == 0 && data != null && data.trim().length() >= 1) {
                        outputStream.write((socket.getLocalPort() + "//" + data + "//" + daqu + Login.getUser().getName() + "//" + Login.getUser().getDj()).getBytes("utf-8"));
                    } else if (num == 2 && data != null && data.trim().length() >= 1) {
                        if (data.length() >= 1) {
                            Log.v("123123213213", data);
                            outputStream.write((socket.getLocalPort() + "//" + data + "// " + daqu + "系统 //" + -2).getBytes("utf-8"));
                        }
                    }
                    outputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    Handler handler = new Handler(new Handler.Callback() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what) {
                case 1:
                    int localPort = socket.getLocalPort();
                    String[] split = ((String) message.obj).split("//");
                    if (split[0].equals(localPort + "")) {
                        //获取内部消息
                        try {
                            MyBean bean = new MyBean(split[1], split[2], Integer.parseInt(split[3]));
                            if (!split[1].trim().equals("") && !split[3].equals("-1")) {
                                if (bean.getDj() != -1 && !bean.getData().trim().equals("denglu" + daqu + Util.getIMEI(MainActivity.this)) && bean.getData().trim().length() >= 1) {
                                    Log.v("liaotian1neibu", bean.toString());
                                    list.add(bean);
                                    // 向适配器set数据
                                    adapter.setData(list);
                                    lv.setAdapter(adapter);
                                }
                            }
                        } catch (Exception e) {
                            e.getMessage();
                        }
                    } else {
                        //获取外来消息
                        try {
                            MyBean bean = new MyBean(split[1], split[2], Integer.parseInt(split[3]));
                            if (!split[1].trim().equals("")) {
                                if (bean.getDj() == -1 && bean.getData().contains("denglu" + daqu) && bean.getName().equals(Login.getUser().getName())) {
                                    ToastUtil.toastLong(MainActivity.this, "账号已再别处登陆");
                                    Working = false;
                                    Intent intent = new Intent(getApplicationContext(), Login.class);
                                    startActivity(intent);
                                    finish();
                                } else if (bean.getDj() == -1 && (bean.getData().contains(Util.getIMEI(MainActivity.this))) && bean.getData().contains("denglu")&&! bean.getName().equals(Login.getUser().getName())) {
                                    ToastUtil.toastLong(MainActivity.this, "登陆已达上限");
                                    Working = false;
                                    Intent intent = new Intent(getApplicationContext(), Login.class);
                                    startActivity(intent);
                                    finish();
                                } else if (bean.getDj() != -1 && !bean.getData().equals("denglu" + daqu + Util.getIMEI(MainActivity.this)) && bean.getData().trim().length() >= 1 && bean.getName().length() < 20 && bean.getDj() < 200 && bean.getDj() > -10) {
                                    Log.v("liaotian1waibu", bean.toString());
                                    list.add(bean);
                                    // 向适配器set数据
                                    adapter.setData(list);
                                    lv.setAdapter(adapter);
                                }
                            }
                        } catch (Exception e) {
                            e.getMessage();
                        }
                    }
                    break;
                case 2:
                    User user = (User) message.obj;
                    if (user != null) {
                        Login.getUser().setDj(user.getDj());
                        Login.getUser().setJy(user.getJy());
                        Login.getUser().setZhuangbei(user.getZhuangbei());
                        Login.getUser().setWq2(user.getWq2());
                        Login.getUser().setHj2(user.getHj2());
                        Login.getUser().setZj2(user.getZj2());
                        Login.getUser().setJz2(user.getJz2());

                        Login.getUser().setMoney(user.getMoney());
                        Login.getUser().setLs1(user.getLs1());
                        Login.getUser().setLs2(user.getLs2());
                        Login.getUser().setLs3(user.getLs3());
                        Login.getUser().setLs4(user.getLs4());
                        Login.getUser().setCw_id(user.getCw_id());
                        Login.getUser().setCwid(user.getCwid());
                        tvJingyan.setText("修为：" + Login.getUser().getJy() + "/" + (Login.getUser().getDj() * Login.getUser().getDj() * Login.getUser().getDj() * Login.getUser().getDj() / 5 + 10));
                        tvMoney.setText("金钱：" + Login.getUser().getMoney());
                        tvName.setText("LV:" + Login.getUser().getDj() + " " + Login.getUser().getName());
                        if (Login.getUser().getDj() > 80) {
                            tvName.setBackground(getResources().getDrawable(R.color.renwudj5));
                        } else if (Login.getUser().getDj() >= 60) {
                            tvName.setBackground(getResources().getDrawable(R.color.renwudj4));
                        } else if (Login.getUser().getDj() >= 40) {
                            tvName.setBackground(getResources().getDrawable(R.color.renwudj3));
                        } else if (Login.getUser().getDj() >= 20) {
                            tvName.setBackground(getResources().getDrawable(R.color.renwudj2));
                        } else if (Login.getUser().getDj() >= 1) {
                            tvName.setBackground(getResources().getDrawable(R.color.renwudj1));
                        }
                    } else {
                        ToastUtil.toast(MainActivity.this, "服务器炸了");
                    }
                    break;
                case 3:
                    user = null;
                    user = (User) message.obj;
                    if (null != user) {
                        ToastUtil.toast(MainActivity.this, user.getStw());
                        Intent intent = new Intent(getApplicationContext(), Login.class);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtil.toast(MainActivity.this, "服务器炸了");
                    }

                    break;
                case 4:
                    user = null;
                    user = (User) message.obj;
                    if (null != user) {
                        int all = user.getDj();
                        int week = user.getJy();
                        qiandao("本周签到第" + week + "天", "当前累计签到第" + all + "天");
                        ToastUtil.toast(MainActivity.this, user.getStw());
                    } else {
                        ToastUtil.toast(MainActivity.this, "服务器炸了");
                    }
                    break;
            }

            return false;
        }
    });


    private void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确认要退出么？");
        builder.setTitle("提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        builder.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dialog();
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        tvMoney.setText(Login.getUser().getMoney() + "");
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onRestart() {
        //获取焦点调用
        super.onRestart();
        getUser();

        Working = true;
        if (!thread.isAlive()) {
            thread = null;
        }
        if (!thread2.isAlive()) {
            thread2 = null;
        }
        if (thread == null) {
            thread = new NeedStopThread();
            thread.start();
        }
        if (thread2 == null) {
            thread2 = new NeedStopThread2();
            thread2.start();
        }
    }

    @Override
    protected void onPause() {
        //活动不可见调用
        super.onPause();
    }

    /**
     * 接收后处理
     *
     * @param messageEvent
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void shuaxing(MessageEvent messageEvent) {
        if (messageEvent.getMessage().equals("SenLin")) {
            tvJingyan.setText("修为：" + Login.getUser().getJy() + "/" + (Login.getUser().getDj() * Login.getUser().getDj() * Login.getUser().getDj() * Login.getUser().getDj() / 5 + 10));
            tvMoney.setText("金钱：" + Login.getUser().getMoney());
            tvName.setText("LV:" + Login.getUser().getDj() + " " + Login.getUser().getName());
            if (Login.getUser().getDj() > 80) {
                tvName.setBackground(getResources().getDrawable(R.color.renwudj5));
            } else if (Login.getUser().getDj() >= 60) {
                tvName.setBackground(getResources().getDrawable(R.color.renwudj4));
            } else if (Login.getUser().getDj() >= 40) {
                tvName.setBackground(getResources().getDrawable(R.color.renwudj3));
            } else if (Login.getUser().getDj() >= 20) {
                tvName.setBackground(getResources().getDrawable(R.color.renwudj2));
            } else if (Login.getUser().getDj() >= 1) {
                tvName.setBackground(getResources().getDrawable(R.color.renwudj1));
            }
        } else if (messageEvent.getMessage().equals("setmoney")) {
            tvMoney.setText("金钱：" + Login.getUser().getMoney());
        } else if (messageEvent.getMessage().equals("xinxi")) {
            fasong(messageEvent.getContent(), 2);//发送系统提示
        } else if (messageEvent.getMessage().equals("user")) {
            getUser();
        }
    }

    private void getUser() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber() + "&passWord=" + Login.getUser().getPassword() + "&need=denglu" + "&banben=" + Login.getVerName(this), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("Login111", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("Login222", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 2;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (thread != null) {
            thread.interrupt();
            Working = false;
            thread = null;
        }
        if (thread2 != null) {
            thread2.interrupt();
            Working = false;
            thread2 = null;
        }
        if (thread2 == null && thread == null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        playingmusic(PAUSE_MUSIC);
        unregisterReceiver(receiver);
    }


    class NeedStopThread extends Thread {
        @Override
        public void run() {
            try {
                socket = new Socket(OkhttpUtil.URL_SOCKET, 10012);
                InputStream inputStream = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    String data = new String(buffer, 0, len);
                    // 发到主线程中 收到的数据
                    Message message = Message.obtain();
                    message.what = 1;
                    message.obj = data;
                    handler.sendMessage(message);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    class NeedStopThread2 extends Thread {
        @Override
        public void run() {
            while (Working) {
                try {
                    sleep(2000);
                    if (Working) {
                        fasong("denglu" + daqu + Util.getIMEI(MainActivity.this), 1);
                    }
                    sleep(60000);
                    Working = true;
                    if (!thread.isAlive()) {
                        thread = null;
                    }
                    if (!thread2.isAlive()) {
                        thread2 = null;
                    }
                    if (thread == null) {
                        thread = new NeedStopThread();
                        thread.start();
                    }
                    if (thread2 == null) {
                        thread2 = new NeedStopThread2();
                        thread2.start();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
